/* 
 * Implementation of the particle system requires 
 * that the data be loaded before starting the loop.
 * Add new Emitters to an array and keep updating them
 * Removing the ones that are done.
 * */

function RandChoice(list){
    var indx = Math.floor(Math.random() * list.length);
    return list[indx];
}

function Particle(pos, vel, img, reverse){
    this.sdt = 2;
    this.adt = 0.1;
    this.alpha = 1.0;
    this.size = 5;
    this.reverse = reverse;
    if(reverse){
        this.alpha = 0.0;
        this.size = 20;
    }
    this.x = pos[0];
    this.y = pos[1];
    this.vel = vel;
    this.img = img;
    this.update = function(){
        this.x = this.x + this.vel[0];
        this.y = this.y + this.vel[1];
        if(this.reverse){
            this.size -= 2;
            this.alpha += 0.1;
        }else{
        this.size += 2;
        this.alpha -= 0.1;
        }
    } 
    this.draw = function(){
        ctx.globalAlpha = this.alpha;
        ctx.drawImage(this.img, this.x-this.size, this.y-this.size, this.size*2, this.size*2);
    }
}


function Emiter(pos, vel, img, repeat, reverse){
    this.reverse = reverse;
    this.particles = new Array();
    this.vel = new Array(2);
    this.pos = new Array(2);
    this.pos[0] = pos[0]; //canvas.width/2 + 100 * Math.cos(Math.PI * 2 * Math.random());
    this.pos[1] = pos[1]; //canvas.height/2 + 100 * Math.sin(Math.PI * 2 * Math.random());
    this.img = img;
    this.repeat = repeat;
    this.vel[0] = vel[0];
    this.vel[1] = vel[1];
    this.done = false;
    //add one particle to the emiter.
    x = this.pos[0] + map.pos[0];
    y = this.pos[1] + map.pos[1];
    //this.particles.push(new Particle(this.pos, this.vel, data.getImage(this.img), this.reverse));
    this.particles.push(new Particle([x,y], this.vel, data.getImage(this.img), this.reverse));

    this.update = function(){
        tmp = new Array();
        for (var i in this.particles){
            this.particles[i].update();
            if(this.reverse && this.particles[i].alpha > 1){
                continue;
            }else if(!this.reverse && this.particles[i].alpha < 0){
                continue;
            }else{
                tmp.push(this.particles[i]);
            }
            ///draw the particles
            this.particles[i].draw();
        }
        this.particles = tmp;   //getting rid of the dead particles.
        if(this.repeat && this.particles.length < 4){
            x = this.pos[0] + map.pos[0];
            y = this.pos[1] + map.pos[1];
            this.particles.push(new Particle([x,y], this.vel, data.getImage(this.img), this.reverse));
        }
        if(this.particles.length == 0){
            this.done = true;
        }
    }
}
